package com.tools.common.serialize;

import android.content.SharedPreferences;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.tools.common.application.BaseApp;

public class SharedPrefRepo implements IRepo {
    private static SharedPrefRepo sRepo = null;
    private static SharedPreferences sPref = null;
    private static Gson sGson = null;

    public static SharedPrefRepo instance() {
        if(sRepo == null) {
            synchronized (SharedPrefRepo.class) {
                if(sRepo == null) {
                    sRepo = new SharedPrefRepo();
                }
            }
        }

        return sRepo;
    }

    private SharedPrefRepo() {
        sPref = BaseApp.appContext().getSharedPreferences(IRepo.REPO_NAME, 0);
        sGson = new Gson();
    }

    @Override
    public <T> void store(String key, T obj) {
        sPref.edit().putString(key, sGson.toJson(obj)).commit();
    }

    @Override
    public <T> T load(String key, Class clazz) {
        String value = sPref.getString(key, null);
        if(TextUtils.isEmpty(value)) {
            return null;
        }

        return (T)sGson.fromJson(value, clazz);
    }
}
